using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.IO.Compression;
using System.Threading;
using System.Diagnostics;

namespace SPTraceView
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Mutex mutex = null;
            bool createdNew = false;
            int secWaiting = 0;
            do
            {
                if (secWaiting > 0) Thread.Sleep(300);
                mutex = new Mutex(true, "~MUTEX~SPTRACEVIEW", out createdNew);

                if (secWaiting > 0) Thread.Sleep(500);
                secWaiting++;
            }
            while (
                !createdNew &&
                secWaiting < 6);

            if (!createdNew)
            {
                MessageBox.Show("Another instance of SPTraceView is already running. Only one instance is allowed.", "Only one instance is allowed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                using (Stream input = Assembly.GetExecutingAssembly().GetManifestResourceStream("SPTraceView.Resource.bin"))
                using (MemoryStream str = new MemoryStream())
                {
                    input.Position = 0;
                    byte[] magic = new byte[4];
                    input.Read(magic, 0, 4);

                    using (DeflateStream zippedStream = new DeflateStream(input, CompressionMode.Decompress))
                    using (BinaryReader reader = new BinaryReader(zippedStream))
                    {
                        const int BUFFER_LEN = 1024;

                        // Don't close/dispose the the stream reader because this will close the input stream as well
                        BinaryWriter writer = new BinaryWriter(str);

                        int bytesRead = 0;
                        byte[] buffer = new byte[BUFFER_LEN];
                        do
                        {
                            bytesRead = reader.Read(buffer, 0, buffer.Length);
                            writer.Write(buffer, 0, bytesRead);
                        }
                        while (bytesRead == BUFFER_LEN);

                        writer.Flush();
                    }

                    Assembly asm = AppDomain.CurrentDomain.Load(str.ToArray());
                    Type type = asm.GetType("SPTraceView.frmMain");
                    object frmMain = Activator.CreateInstance(type);

                    Form frm = frmMain as Form;
                    try
                    {
                        Application.Run();
                    }
                    finally
                    {
                        frm.Dispose();
                        frm = null;
                    }
                }
            }
            finally
            {
                if (createdNew)
                    mutex.ReleaseMutex();
            }
        }
    }
}